"use client";
import { defaultEditorContent } from "@/lib/content";
import { novelcopy } from "@/lib/copyContent";
import { Button } from "@/components/ui/button"
import {
  EditorCommand,
  EditorCommandEmpty,
  EditorCommandItem,
  EditorCommandList,
  EditorContent,
  type EditorInstance,
  EditorRoot,
  type JSONContent,
} from "novel";
import { ImageResizer, handleCommandNavigation,MarkdownExtension } from "novel/extensions";
import { MermaidExtension } from '@/components/tailwind/MermaidExtension'
import { useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { defaultExtensions } from "./extensions";
import { ColorSelector } from "./selectors/color-selector";
import { LinkSelector } from "./selectors/link-selector";
import { NodeSelector } from "./selectors/node-selector";
import { MathSelector } from "./selectors/math-selector";
import { Separator } from "@/components/ui/separator";

import { handleImageDrop, handleImagePaste } from "novel/plugins";
import GenerativeMenuSwitch from "./generative/generative-menu-switch";
import { uploadFn } from "./image-upload";
import { TextButtons } from "./selectors/text-buttons";
import { slashCommand, suggestionItems } from "./slash-command";
import { ProductCopy } from "@/types/Model";
import { useRouter } from 'next/navigation'
import hljs from "highlight.js"

const markdownExtension = MarkdownExtension.configure({
  // 配置选项
  html: true, // 是否允许 HTML
  linkify: true, // 自动将 URL 转换为链接
  breaks: false, // 将换行符转换为 <br>
});
// const extensions = [...defaultExtensions, slashCommand,markdownExtension];
const extensions = [...defaultExtensions, slashCommand, markdownExtension, MermaidExtension]

interface TailwindAdvancedEditorProps {
  copy?: ProductCopy; // You might want to specify a more specific type here
  saveCopy?: (copy: ProductCopy) => Promise<void>;
}
declare global {
  interface Window {
    editorInstance: EditorInstance;
  }
}

const TailwindAdvancedEditor = ({ copy, saveCopy }: TailwindAdvancedEditorProps) => {
  const [initialContent, setInitialContent] = useState<null | JSONContent>(null);
  const [saveStatus, setSaveStatus] = useState("unSaved");
  const [charsCount, setCharsCount] = useState<number>(0);
  const router = useRouter();

  const [editorInstance, setEditorInstance] = useState<EditorInstance | null>(null); // 新增状态


  const [openNode, setOpenNode] = useState(false);
  const [openColor, setOpenColor] = useState(false);
  const [openLink, setOpenLink] = useState(false);
  const [openAI, setOpenAI] = useState(false);
  const [openAudio,setOpenAudio] = useState(false);

  //Apply Codeblock Highlighting on the HTML from editor.getHTML()
  const highlightCodeblocks = (content: string) => {
    const doc = new DOMParser().parseFromString(content, 'text/html');
    doc.querySelectorAll('pre code').forEach((el) => {
      // @ts-ignore
      // https://highlightjs.readthedocs.io/en/latest/api.html?highlight=highlightElement#highlightelement
      hljs.highlightElement(el);
    });
    return new XMLSerializer().serializeToString(doc);
  };




  const debouncedUpdates = useDebouncedCallback(async (editor: EditorInstance) => {
    try {
      const json = editor.getJSON();
      const textContent = editor.getText();
      const chineseCharCount = (textContent.match(/[\u4e00-\u9fa5]/g) || []).length;
      const wordCount = textContent.split(/\s+/).filter(Boolean).length;
      const totalCount = chineseCharCount + wordCount;
      
      setCharsCount(totalCount);
      
      // 使用requestIdleCallback优化性能
      if ('requestIdleCallback' in window) {
        window.requestIdleCallback(() => {
          localStorage.setItem("html-content", highlightCodeblocks(editor.getHTML()));
          localStorage.setItem("novel-content", JSON.stringify(json));
          localStorage.setItem("markdown", editor.storage.markdown.getMarkdown());
        });
      } else {
        localStorage.setItem("html-content", highlightCodeblocks(editor.getHTML()));
        localStorage.setItem("novel-content", JSON.stringify(json));
        localStorage.setItem("markdown", editor.storage.markdown.getMarkdown());
      }
      
      setSaveStatus("未保存");
    } catch (error) {
      console.error('编辑器更新错误:', error);
    }
  }, 500);

  useEffect(() => {
    if (copy?.content) {
      try {
        // 清除旧内容
        localStorage.removeItem("novel-content");
        localStorage.removeItem("markdown");
         // 重置编辑器实例
         if (editorInstance) {
          editorInstance.destroy();
          setEditorInstance(null);
        }
        
        const parsedContent = JSON.parse(copy.content);
        setInitialContent(parsedContent);
      } catch (error) {
        console.error('Failed to parse copy content:', error);
        setInitialContent(null);
      }
    } else {
      setInitialContent(novelcopy(copy?.title, "开始编写"));
    }
  }, [copy]); 

  const saveNovelCopy = async (editor?: EditorInstance) => {
    try {
      if (!copy || !saveCopy) {
        setSaveStatus('保存失败: 缺少必要参数');
        return;
      }
      
      setSaveStatus('保存中...');
      
      // 添加性能监控
      const startTime = performance.now();
      
      let content, markdownContent;
      try {
        content = editor ? editor.getJSON() : JSON.parse(localStorage.getItem('novel-content') || 'null');
        markdownContent = editor ? editor.storage.markdown.getMarkdown() : localStorage.getItem('markdown') || '';

        // 提取标题
        if (content?.content?.length > 0) {
          const heading = content.content.find((item: any) => item.type === 'heading');
          if (heading?.content?.[0]?.text) {
            copy.title = heading.content[0].text;
          }
        }
      } catch (parseError) {
        console.error('内容解析错误:', parseError);
        setSaveStatus('保存失败: 内容解析错误');
        return;
      }
      
      const updatedCopy: ProductCopy = {
        ...copy,
        content: JSON.stringify(content) || '',
        md_content: markdownContent || '',
      };

      await saveCopy(updatedCopy);
      
      // 记录保存耗时
      const endTime = performance.now();
      console.log(`保存耗时: ${(endTime - startTime).toFixed(2)}ms`);
      
      setSaveStatus('已保存');
      
      // 3秒后自动清除保存状态
      setTimeout(() => {
        setSaveStatus(prev => prev === '已保存' ? '' : prev);
      }, 3000);
    } catch (error) {
      console.error('保存失败:', error);
      setSaveStatus('保存失败: ' + (error instanceof Error ? error.message : String(error)));
      
      // 5秒后自动清除错误状态
      setTimeout(() => {
        setSaveStatus('');
      }, 5000);
    }
  };

  const handleExport = () => {
    if (!copy?.md_content) return;
    
    try {
      const blob = new Blob([new TextEncoder().encode(copy.md_content)], { 
        type: 'text/markdown;charset=utf-8' 
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${copy.title || 'untitled'}.md`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Export error:', error);
    }
  };


  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // 检查是否是 Ctrl/Cmd + S
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();  // 阻止浏览器默认保存行为
        if (editorInstance) {
          saveNovelCopy(editorInstance);     // 调用保存函数
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [saveNovelCopy]);  // 依赖 saveNovelCopy 以确保最新引用

  if (!initialContent) return null;

  return (
    <div className="relative w-full max-w-screen-xl">
      <div className="flex absolute left-5 top-5 z-10 mb-5 gap-2">
        <div className="rounded-lg bg-accent px-2 py-1 text-sm ">{saveStatus}</div>
        <div className={charsCount ? "rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground" : "hidden"}>
          {charsCount} Words
        </div>
      </div>
      <div className="flex absolute right-5 top-5 z-10 mb-5 gap-2">
        
        <Button 
          variant="outline" 
          size="sm"
          onClick={() => saveNovelCopy(window.editorInstance)} 
          className="rounded-lg bg-accent px-2 py-1 text-sm  hover:bg-accent/80"
        >
          保存
        </Button>
        
        {/* <Button 
          variant="outline" 
          size="sm"
          onClick={handleExport}
          className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground hover:bg-accent/80"
        >
          导出
        </Button> */}
        <Button
          variant="outline"
          size="sm"
          onClick={() => window.open(`/notion/copy/${copy?.id}`, '_blank')}
          className="rounded-lg bg-accent px-2 py-1 text-sm text-muted-foreground hover:bg-accent/80"
        >
          分享或打印
        </Button>
      </div>
      <EditorRoot>
        <EditorContent
          initialContent={initialContent}
          extensions={extensions}
          className="relative p-24 min-h-[700px] w-full max-w-screen-xl border-muted bg-background sm:mb-[calc(20vh)] sm:rounded-lg sm:border sm:shadow-lg"
          editorProps={{
            handleDOMEvents: {
              keydown: (_view, event) => handleCommandNavigation(event),
            },
            handlePaste: (view, event) => handleImagePaste(view, event, uploadFn),
            handleDrop: (view, event, _slice, moved) => handleImageDrop(view, event, moved, uploadFn),
            attributes: {
              class:
                "prose prose-lg dark:prose-invert prose-headings:font-title font-default focus:outline-none max-w-full",
            },
          }}
          onUpdate={({ editor }) => {
            debouncedUpdates(editor);
            // setSaveStatus("Unsaved");
            setEditorInstance(editor)
          }}
          slotAfter={<ImageResizer />}
        >
          <EditorCommand className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-md border border-muted bg-background px-1 py-2 shadow-md transition-all">
            <EditorCommandEmpty className="px-2 text-muted-foreground">No results</EditorCommandEmpty>
            <EditorCommandList>
              {suggestionItems.map((item:any) => (
                <EditorCommandItem
                  value={item.title}
                  onCommand={(val) => item.command?.(val)}
                  className="flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm hover:bg-accent aria-selected:bg-accent"
                  key={item.title}
                >
                  <div className="flex h-10 w-10 items-center justify-center rounded-md border border-muted bg-background">
                    {item.icon}
                  </div>
                  <div>
                    <p className="font-medium">{item.title}</p>
                    <p className="text-xs text-muted-foreground">{item.description}</p>
                  </div>
                </EditorCommandItem>
              ))}
            </EditorCommandList>
          </EditorCommand>

          <GenerativeMenuSwitch open={openAI} onOpenChange={setOpenAI}>
            <Separator orientation="vertical" />
            <NodeSelector open={openNode} onOpenChange={setOpenNode} />
            <Separator orientation="vertical" />

            <LinkSelector open={openLink} onOpenChange={setOpenLink} />
            <Separator orientation="vertical" />
            <MathSelector />
            <Separator orientation="vertical" />
            <TextButtons />
            <Separator orientation="vertical" />
            <ColorSelector open={openColor} onOpenChange={setOpenColor} />
          </GenerativeMenuSwitch>
        </EditorContent>
      </EditorRoot>
    </div>
  );
};

export default TailwindAdvancedEditor;
